package demo.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.Base64;
import java.util.NoSuchElementException;
import java.util.Optional;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/11/4 上午10:32
 * @UpdateDate:
 * @Description:
 */
public class ExecuteArchery {

    public static void main(String[] args) {
        touch_token_from_archery(
                ENV.PRD,
                "lbs_cm_microservice",
                "select `token` from `cm_user` where `name` = 'admin';"
        );
    }

    public static String touch_token_from_archery(ENV env, String database, String sql_script){
        // 浏览器驱动.
        System.setProperty("webdriver.chrome.driver", "/Users/icasue/Desktop/lbs-server-plugins/icasue-plugins-demos/icasue-demo-selenium/src/main/resources/drivers/chromedriver_98");
        // 创建浏览器驱动
        ChromeDriver driver = null;
        String token = null;
        try {
            // 打开网站主页[redirect to /login].
            driver = new ChromeDriver();
            driver.get("https://bt-sql-audit.btpoc.com/");

            // 尝试获取已经创建并经过授权的session.
            Optional<Cookie> sessionOptional = Optional.ofNullable(driver.manage().getCookieNamed("sessionid"));
            if(!sessionOptional.isPresent()){
                // session 不存在时需要获取登录相关DOM, 并执行.
                WebElement username = driver.findElement(By.id("inputUsername"));
                username.sendKeys(new String(Base64.getDecoder().decode("cWlhb2hhbmc=")));

                WebElement password = driver.findElement(By.id("inputPassword"));
                password.sendKeys(new String(Base64.getDecoder().decode("MTc2MTE2NjA5MTg=")));

                WebElement buttonLogin = driver.findElement(By.id("btnLogin"));
                buttonLogin.click();

                // 等待页面tab跳转，加载 root/sqlquery/
                Boolean wait_complete = new WebDriverWait(driver, Duration.ofSeconds(3))
                        .until($driver -> $driver.getTitle().equals("Archery-SQL审核查询平台"));

                // 检测用户名密码是否正确
                //while (!driver.getTitle().equals("Archery-SQL审核查询平台")){ Thread.sleep(500); }
            }

            // 切换到查询页面.
            //driver.navigate().to("https://bt-sql-audit.btpoc.com/sqlquery/");

            // 选择实例 下拉菜单.
            WebElement instance_name = new FluentWait<WebDriver>(driver)
                    .withTimeout(Duration.ofSeconds(3))
                    .pollingEvery(Duration.ofSeconds(1))
                    .ignoring(NoSuchElementException.class)
                    .until($driver -> $driver.findElement(By.name("instance_name")));
            new Select(instance_name).selectByValue(env.instance_name);

            // 选择数据库
            WebElement db_name = new FluentWait<WebDriver>(driver)
                    .withTimeout(Duration.ofSeconds(3))
                    .pollingEvery(Duration.ofSeconds(1))
                    .ignoring(NoSuchElementException.class)
                    .until($driver -> $driver.findElement(By.id("db_name")));
            new Select(db_name).selectByValue(database);

            // 写入SQL文本.
            WebElement textarea = driver.findElement(By.tagName("textarea"));
            textarea.sendKeys(sql_script);

            // 查询按钮点击
            driver.findElement(By.id("btn-sqlquery")).click();

            // 获取查询结果, #query_result1 -> th[0] -> tr[1]
            Thread.sleep(1000);
            WebElement token_cell = driver.findElement(By.cssSelector("#query_result1 td"));
            token = token_cell.getText();
        }catch (Throwable e){
            e.printStackTrace();
        }finally {
            if(driver != null){
                // 退出驱动，退出驱动进程，远程驱动进程,
                // 关闭当前驱动打开的所有tab或者window， 关闭浏览器，清理session.
                driver.quit();
            }
        }

        return token;
    }

    public enum ENV{
        DEV("开发环境_Mysql_10.21.1.7"),
        TEST("测试环境_MySQL_10.13.4.16"),
        SIT("SIT环境_Mysql_10.22.4.30"),
        PRE("智能座舱Pre_MySQL_ro"),
        PRD("智能座舱Prd_MySQL_ro");
        // 实例名称
        public final String instance_name;
        ENV(String instance_name){
            this.instance_name = instance_name;
        }
    }
}
